/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.storage.naive.internal;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Property;
import org.apache.felix.ipojo.annotations.Provides;
import org.osami.gateway.sensor.data.AbstractSenseData;
import org.osami.gateway.sensor.data.SenseData;
import org.osami.gateway.storage.ISenseDataStorage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Provides
@Instantiate
public class NaiveSenseDataStorage implements ISenseDataStorage {

    /**
     * File name of the input file.
     */
    private static final String STORAGE_INPUT_FILE = "NaiveSenseDataStorageInput.txt";

    /**
     * File name of the output file.
     */
    private static final String STORAGE_OUTPUT_FILE = "NaiveSenseDataStorageOutput.txt";

    /**
     * System property name activating data filtering at startup.
     */
    public static final String PROPERTY_FILTER_REDUNDANT = "OSAMI_NAIVE_STORAGE_FILTER_REDUNDANT_UPON_RELOAD";

    /**
     * 1 minute expressed in milliseconds.
     */
    private static final int ONE_MINUTE = 60 * 1000;

    /**
     * Period size in seconds.
     */
    @Property(name = "period.size", value = "172800")
    private long periodSize;

    /**
     * Maximum count of stored sense data.
     */
    @Property(name = "senses.max", value = "65536")
    private int maxSenseData;

    private Set<SenseData> datas;

    private FileWriter writer;

    public NaiveSenseDataStorage() {
        this(172800, 65536);
    }

    public NaiveSenseDataStorage(long periodSize, int maxSenseData) {
        this.periodSize = periodSize;
        this.maxSenseData = maxSenseData;

        Set<SenseData> fasterData = new TreeSet<SenseData>(new TimestampComparator());
        Map<String, SenseData> redundancyEliminationMap = new TreeMap<String, SenseData>();
        Map<String, SenseData> latestData = new TreeMap<String, SenseData>();

        this.writer = null;

        try {
            BufferedReader reader;
            String s = "";

            writer = new FileWriter(STORAGE_OUTPUT_FILE, true);
            writer.write("----------\n");
            writer.flush();

            File input = new File(STORAGE_INPUT_FILE);

            // Process the input file only if it exists (and is a file, if it is a directory, we don't care)
            if (input.isFile()) {

                // Create Reader
                reader = new BufferedReader(new FileReader(input));

                while ((s = reader.readLine()) != null) {
                    SenseData sd = new NaiveSenseData(s);

                    if (System.getenv(PROPERTY_FILTER_REDUNDANT) == null) {
                        fasterData.add(sd);
                    }
                    else {
                        String senseId = sd.getSenseId();
                        SenseData sd2 = redundancyEliminationMap.get(senseId);
                        if (sd2 == null) {
                            // New sense ID: always add.
                            //System.out.println("Initializing for " + senseId);
                            redundancyEliminationMap.put(senseId, sd);
                            fasterData.add(sd);
                            writer.write(sd.toString());
                            writer.write("\n");
                            writer.flush();
                        }
                        else {
                            if (sd.getValue().equals(sd2.getValue())) {
                                // Same value.
                                if (sd.getTimeStamp() >= sd2.getTimeStamp() + ONE_MINUTE) {
                                    // Same value and at least 1 minute since previous SenseData: add.
                                    //System.out.println("Adding same value " + sd.getTimeStamp() + " " + sd2.getTimeStamp());
                                    redundancyEliminationMap.put(senseId, sd);
                                    fasterData.add(sd);
                                    writer.write(sd.toString());
                                    writer.write("\n");
                                    writer.flush();
                                }
                            }
                            else {
                                // Different value: always add.
                                //System.out.println("Adding different value " + sd.getValue() + " " + sd2.getValue());
                                redundancyEliminationMap.put(senseId, sd);
                                fasterData.add(latestData.get(senseId));
                                fasterData.add(sd);
                                writer.write(sd.toString());
                                writer.write("\n");
                                writer.flush();
                            }
                        }
                        latestData.put(senseId, sd);
                    }
                }
            }
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }

        this.datas = new CopyOnWriteArraySet<SenseData>(fasterData);
    }

    public void store(SenseData data) {
        synchronized(this) {
            reduce();
            if (writer != null) {
                try {
                    writer.write(data.toString());
                    writer.write("\n");
                    writer.flush();
                }
                catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
            datas.add(data);
        }
    }

    private void reduce() {
        if (datas.size() > maxSenseData) {
            // Too much datas, remove the older one (the first)
            Iterator<SenseData> i = iteratorInternal();
            datas.remove(i.next());
        }

        long current = System.currentTimeMillis();
        long limitTimestamp = current - (periodSize * 1000);

        // Kind of ugly, but it works ;)
        // I just want to remove the first entry if it is too old.
        // As soon as there are no more entries to cleanup, we stop
        while (cleanFirstEntry(limitTimestamp));
    }

    private boolean cleanFirstEntry(long limitTimestamp) {
        // Important: do not use directly iterator here, that should cause infinite loop !!!
        Iterator<SenseData> i = iteratorInternal();
        SenseData sense = null;
        if (i.hasNext()) {
            sense = i.next();
            if (sense.getTimeStamp() < limitTimestamp) {
                datas.remove(sense);
                return true;
            }
        }
        return false;
    }

    public void cleanup() {
        synchronized (this) {
            datas.clear();
        }
    }

    public Iterator<SenseData> iterator() {
        synchronized (this) {
            reduce();
            return iteratorInternal();
        }
    }

    private Iterator<SenseData> iteratorInternal() {
        return datas.iterator();
    }


    private class NaiveSenseData extends AbstractSenseData {

        public NaiveSenseData(String serializedForm) {
            super(serializedForm);
        }
    }
}
